package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.Article;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author shkstart
 * @create 2023-01-11-21:15
 */
@WebServlet("/artdetail")
public class ArtDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aidstr = req.getParameter("aid");
        String msg = "位置参数来自artdeatil";
        Article article = new Article();
        //1.进行非空判断
        if (!StrUtil.isBlank(aidstr)) {
            int aid = Integer.valueOf(aidstr);

            //2.1得到连接、
            Connection connection = DBUtils.getConnection();
            //2.2拼接sql，得到执行器
            String sql = "select * from article where aid = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            //2.3执行执行器，得到结果
            statement.setInt(1,aid);
            ResultSet resultSet = statement.executeQuery();
            if(resultSet.next()){//只存在一个aid
                article.setAid(resultSet.getInt("aid"));
                article.setTitle(resultSet.getString("title"));
                article.setContext(resultSet.getString("context"));
                String ctime = resultSet.getString("createtime");
                article.setCreatetime(ctime.substring(0,ctime.lastIndexOf(".")));
                article.setReadcount(resultSet.getInt("readcount"));
            }
            DBUtils.close(resultSet,statement,connection);
            msg = "成功到达ArtDetaileServlet";
        }else{
            msg = "参数错误";
        }
        //将结果返回给前端
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(ResultUtils.toResult(200,article,msg))
        );
    }
}
